package com.szgr.baoyin.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.CartListAdapter;
import com.szgr.baoyin.model.CartProduct;
import com.szgr.baoyin.model.OrderGoods;
import com.szgr.baoyin.model.OrderMember;
import com.szgr.baoyin.model.Product;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class CartActivity extends BaseActivity implements CartListAdapter.CartInterface, CompoundButton.OnCheckedChangeListener {

    private static final int HAS_ADDRESS = 80;
    private static final int NO_ADDRESS = 81;
    private CheckBox cb_check;
    private TextView tv_money;
    private List<Product> data;
    private CartListAdapter cartListAdapter;
    private View cartCenter;
    private View cartBottom;
    private ArrayList<OrderGoods> mData;
    private HashMap<String, Object> hashMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_cart);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("购物车");
    }

    @Override
    public void initView() {
        data = new ArrayList<>();

        ListView cartListView = (ListView) findViewById(R.id.cart_list_view);
        cartListAdapter = new CartListAdapter(this, data, this);
        cartListView.setAdapter(cartListAdapter);

        cb_check = (CheckBox) findViewById(R.id.cart_check_all);
        cb_check.setOnClickListener(this);
        tv_money = (TextView) findViewById(R.id.cart_money);

        cartCenter = findViewById(R.id.cart_center);
        cartBottom = findViewById(R.id.cart_bottom);
        findViewById(R.id.cart_go_store).setOnClickListener(this);
        findViewById(R.id.cart_submit).setOnClickListener(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        getCart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        getCart();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 77:
                    cartCenter.setVisibility(View.VISIBLE);
                    cartBottom.setVisibility(View.GONE);
                    MyApplication.getmInstance().setCartNum(0);
                    break;
                case 78:
                    cartCenter.setVisibility(View.GONE);
                    cartBottom.setVisibility(View.VISIBLE);
                    MyApplication.getmInstance().setCartNum((int) msg.obj);
                    break;
                case HAS_ADDRESS:
                    HashMap<String,String> map = (HashMap<String, String>) msg.obj;
                    Intent hasIntent = new Intent(CartActivity.this, MyOrderDetailActivity.class);
                    hasIntent.putExtra("address_map", map);
                    hasIntent.putExtra("mData",mData);
                    hasIntent.putExtra("hashMap",hashMap);
                    hasIntent.putExtra("type",Constant.TYPE_03);
                    startActivity(hasIntent);
                    break;
                case NO_ADDRESS:
                    Intent noIntent = new Intent(CartActivity.this, MyOrderDetailActivity.class);
                    noIntent.putExtra("mData",mData);
                    noIntent.putExtra("hashMap",hashMap);
                    noIntent.putExtra("type",Constant.TYPE_03);
                    startActivity(noIntent);
                    break;
            }
        }
    };

    /**
     * 购物车
     */
    private void getCart() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_GET_CART,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---get cart-->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            if ("200".equals(code) && jsonObject.has("datas")) {
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                if (datas.has("cart_list")) {
                                    JSONArray cart_list = datas.getJSONArray("cart_list");
                                    Gson gson = new Gson();
                                    List<CartProduct> list = gson.fromJson(cart_list.toString(), new TypeToken<List<CartProduct>>() {
                                    }.getType());
                                    if (list.size() == 0) {
                                        mHandler.obtainMessage(77).sendToTarget();
                                    } else {
                                        mHandler.obtainMessage(78, list.size()).sendToTarget();
                                    }
                                    data.clear();
                                    for (CartProduct cp : list) {
                                        Product p = new Product();
                                        p.setGoods_id(cp.getGoods_id());
                                        p.setName(cp.getGoods_name());
                                        p.setNewPrice(cp.getGoods_price());
                                        p.setCount(cp.getGoods_num());
                                        p.setImgUrl(cp.getGoods_image_url());
                                        p.setCart_id(cp.getCart_id());
                                        data.add(p);
                                    }
                                    cartListAdapter.setData(data);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.cart_check_all:
                cb_check.setChecked(!cb_check.isChecked());
                for (Product p : data) {
                    p.setIsChecked(!cb_check.isChecked());
                }
                cartListAdapter.notifyDataSetChanged();
                break;
            case R.id.cart_go_store:
                startActivity(new Intent(this, AccessoryStoreActivity.class));
                break;
            case R.id.cart_submit:
                boolean flag = false;
                for (Product p : data) {
                    if (p.isChecked()) {
                        flag = true;
                        break;
                    }
                }
                if (flag) {
                    submitOrder();
                } else {
                    ToastUtils.showToast("请选择至少一件商品");
                }
                break;
        }
    }

    /**
     * 提交订单
     */
    private void submitOrder() {
        final StringBuffer sb = new StringBuffer();
        for (int i = 0; i < data.size(); i++) {
            Product p = data.get(i);
            if (p.isChecked()) {
                if (i == data.size() - 1) {
                    sb.append(p.getCart_id() + "|" + p.getCount());
                } else {
                    sb.append(p.getCart_id() + "|" + p.getCount() + ",");
                }
            }
        }
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_SUBMIT_ORDER,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("------>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.has("datas")) {
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                if (datas.has("vat_hash")) {
                                    String vat_hash = datas.optString("vat_hash");
                                    String freight_hash = datas.optString("freight_hash");
                                    JSONObject offpay = datas.optJSONObject("offpay");


                                    hashMap = new HashMap<>();
                                    hashMap.put("vat_hash", vat_hash);
                                    hashMap.put("freight_hash", freight_hash);

                                    JSONObject store_cart_list = datas.getJSONObject("store_cart_list");
                                    JSONObject six = store_cart_list.getJSONObject("6");
                                    JSONArray goods_list = six.getJSONArray("goods_list");
                                    Gson gson = new Gson();
                                    mData = gson.fromJson(goods_list.toString(), new TypeToken<List<OrderGoods>>() {
                                    }.getType());

                                    JSONObject jsonObject1 = datas.optJSONObject("store_points_list");
                                    Iterator<String> keys = jsonObject1.keys();
                                    while(keys.hasNext()){
                                        JSONObject jsonObject2 = jsonObject1.getJSONObject(keys.next());
                                        OrderMember orderMember = gson.fromJson(jsonObject2.toString(), OrderMember.class);
                                        hashMap.put("orderMember",orderMember);
                                    }

                                    Object address_info = datas.get("address_info");
                                    if (address_info instanceof JSONObject) {
                                        String offpay_hash = offpay.optString("offpay_hash");
                                        hashMap.put("offpay_hash", offpay_hash);
                                        //TODO 有地址信息
                                        JSONObject addJson = (JSONObject) address_info;
                                        HashMap<String, String> map = new HashMap<>();
                                        map.put("address_id", addJson.getString("address_id"));// "430",
                                        map.put("member_id", addJson.getString("member_id"));// "835",
                                        map.put("true_name", addJson.getString("true_name"));// "\u4efb\u91d1\u9e4f",
                                        map.put("area_id", addJson.getString("area_id"));// "37",
                                        map.put("city_id", addJson.getString("city_id"));// "36",
                                        map.put("area_info", addJson.getString("area_info"));// "\u5317\u4eac\u5317\u4eac\u5e02\u4e1c\u57ce\u533a",
                                        map.put("address", addJson.getString("address"));// "\u4fdd\u94f6\u673a\u5e8a",
                                        map.put("tel_phone", addJson.getString("tel_phone"));// "",
                                        map.put("mob_phone", addJson.getString("mob_phone"));// "18501967780",
                                        map.put("is_default", addJson.getString("is_default"));// "0"

                                        mHandler.obtainMessage(HAS_ADDRESS,map).sendToTarget();

                                    } else if (address_info instanceof JSONArray) {
                                        //TODO 没有地址信息
                                        mHandler.obtainMessage(NO_ADDRESS).sendToTarget();
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                map.put("cart_id", sb.toString());
                map.put("ifcart", "1");
                System.out.println("-----params---->" + map.toString());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void cartBack(double money, boolean isAllCheck) {
        cb_check.setChecked(isAllCheck);
        tv_money.setText(money + "");
    }

    @Override
    public void cartBack(int position) {
        Product product = data.get(position);
        deleteCart(product);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    }

    /**
     * 删除条目
     */
    /**
     * 加入购物车
     */
    private void deleteCart(final Product p) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_DELETE_CART,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.has("datas")) {
                                Object datas = jsonObject.get("datas");
                                if (datas instanceof String) {
                                    String str = (String) datas;
                                    if ("1".equals(str)) {
                                        //删除成功
                                        getCart();
                                    }
                                } else if (datas instanceof JSONObject) {
                                    String error = ((JSONObject) datas).getString("error");
                                    ToastUtils.showToast(error);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                map.put("cart_id", p.getCart_id());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }
}
